package com.cloudbroker.bcs.platform.dav.common.ext.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Created by xuyn15828 on 2016/3/26.
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper{
    private static final String UNICODE_PREFIX = "@$%^&*unicode_prefix*&^%$@";
    private static final Logger logger = LoggerFactory.getLogger(XssHttpServletRequestWrapper.class);
    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request
     * @throws IllegalArgumentException if the request is null
     */
    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        return htmlEncode(super.getHeader(name));
    }

    @Override
    public String getQueryString() {
        return htmlEncode(super.getQueryString());
    }

    @Override
    public String getParameter(String name) {
        return htmlEncode(super.getParameter(name));
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] paramterValues = super.getParameterValues(name);
        if( null == paramterValues || 0 == paramterValues.length )
            return paramterValues;
        for(int i = 0 ; i < paramterValues.length ; i++ ) {
            paramterValues[i] = htmlEncode(paramterValues[i]);
        }
        return paramterValues;
    }

    private static String htmlEncode(String str) {
        if (str == null || str.trim().equals("")) return str;
        StringBuilder encodeStrBuilder = new StringBuilder();
        for (int i = 0, len = str.length(); i < len; i++) {
            encodeStrBuilder.append(htmlEncode(str.charAt(i)));
        }
        try {
            return new String(encodeStrBuilder.toString().getBytes("utf-8"), "utf-8");
        } catch (Exception e) {
            logger.info("html encode error... ", e);
            return encodeStrBuilder.toString();
        }
    }

    private static String htmlEncode(char c) {
        switch(c) {
            case '<':
                return"&lt;";
            case '>':
                return"&gt;";
            default:
                return c +"";
        }
    }
}
